package app

import (
	"fmt"
	"os"
	"runtime"
	"strings"
	"time"

	"git.inedcn.com/ined/cmn"
	"git.inedcn.com/ined/cmn/dotenv"
	"github.com/casbin/casbin"
	xormadapter "github.com/casbin/xorm-adapter"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
)

var (
	db               *xorm.Engine
	dbScszl          *xorm.Engine
	dbCasbinEnforcer *casbin.Enforcer
)

func init() {
	_, filename, _, _ := runtime.Caller(0)
	path := strings.Split(filename, "/")
	env := fmt.Sprintf("%s/.env", strings.Join(path[:len(path)-3], "/"))
	dotenv.Load(env)

	//dsn := GetEnv("DB_URL")
	var err error
	engine, err := xorm.NewEngine("mysql", cmn.GetEnv("DB_HZD"))
	local, _ := time.LoadLocation("Asia/Shanghai")
	engine.SetTZLocation(local)
	engine.SetTZDatabase(local)
	engine.SetConnMaxLifetime(time.Hour)
	engine.SetMaxIdleConns(100)
	engine.SetMaxOpenConns(100)
	engine.ShowSQL(true)
	engine.Logger().SetLevel(log.LOG_DEBUG)
	db = engine

	initDBScszl()
	//db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
	//  Logger: logger.Default.LogMode(logger.Info),
	//})
	if err != nil {
		println(err)
	}
}

func DBScszl() *xorm.Engine {
	return dbScszl
}

func DB() *xorm.Engine {
	return db
}

func initDBScszl() {
	engine, _ := xorm.NewEngine("mysql", cmn.GetEnv("DB_HZD"))
	local, _ := time.LoadLocation("Asia/Shanghai")
	engine.SetTZLocation(local)
	engine.SetTZDatabase(local)
	engine.SetConnMaxLifetime(time.Hour)
	engine.SetMaxIdleConns(100)
	engine.SetMaxOpenConns(100)
	engine.ShowSQL(true)
	engine.Logger().SetLevel(log.LOG_DEBUG)
	dbScszl = engine
}

func GetEnv(args ...string) string {
	argsLen := len(args)
	if argsLen == 0 {
		return ""
	}
	if value, ok := os.LookupEnv(args[0]); ok {
		return value
	}
	if argsLen > 1 {
		return args[1]
	}
	return ""
}

func initCasbin(dbUrl string) (*casbin.Enforcer, error) {
	a := xormadapter.NewAdapter("mysql", dbUrl+"&")
	e := casbin.NewEnforcer(cmn.GetEnv("DATA_DIR")+"/casbin/model.conf", a)

	err := e.LoadPolicy()
	if err != nil {
		return nil, err
	}

	dbCasbinEnforcer = e

	return e, nil
}

func CasbinEnforcer() *casbin.Enforcer {
	return dbCasbinEnforcer
}
